package com.firefly.mobile.app.main;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.LinkedBlockingQueue;

import org.apache.cordova.CordovaActivity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;

import com.firefly.app.biz.yhc.service.YHCService;
import com.firefly.app.biz.yhc.service.YHCServiceImpl;
import com.firefly.app.cordova.plugins.HomePlugin;
import com.firefly.mobile.app.util.SytLog;
import com.umeng.analytics.MobclickAgent;
import com.xiaomi.market.sdk.UpdateResponse;
import com.xiaomi.market.sdk.UpdateStatus;
import com.xiaomi.market.sdk.XiaomiUpdateAgent;
import com.xiaomi.market.sdk.XiaomiUpdateListener;

public class FireflyMobileActivity extends CordovaActivity 
{
	
	protected LinearLayout all;
	
	protected LinearLayout top;
	
	private Context mContext;
	
    /**
     * 消息队列
     */
    private static LinkedBlockingQueue<String> sytActivityBlockingQueue = new LinkedBlockingQueue<String>();

    
    
    
	public static void sendMsgToSytActivity(String msg){
		sytActivityBlockingQueue.add(msg);
	}
	
	
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
//    	MobclickAgent.setDebugMode( true );
    	mContext = this;
        super.onCreate(savedInstanceState);
        super.init();
        
        XiaomiUpdateAgent.setUpdateAutoPopup(false);
        XiaomiUpdateAgent.setUpdateListener(new XiaomiUpdateListener() {

            @Override
            public void onUpdateReturned(int updateStatus, UpdateResponse updateInfo) {
                switch (updateStatus) {
                    case UpdateStatus.STATUS_UPDATE:
                         // 有更新， UpdateResponse为本次更新的详细信息
                         // 其中包含更新信息，下载地址，MD5校验信息等，可自行处理下载安装
                         // 如果希望 SDK继续接管下载安装事宜，可调用
                    	alarmUpdate(updateInfo);
                         break;
                     case UpdateStatus.STATUS_NO_UPDATE:
                        // 无更新， UpdateResponse为null
                        break;
                    case UpdateStatus.STATUS_NO_WIFI:
                        // 设置了只在WiFi下更新，且WiFi不可用时， UpdateResponse为null
                        break;
                    case UpdateStatus.STATUS_NO_NET:
                        // 没有网络， UpdateResponse为null
                        break;
                    case UpdateStatus.STATUS_FAILED:
                        // 检查更新与服务器通讯失败，可稍后再试， UpdateResponse为null
                        break;
                    case UpdateStatus.STATUS_LOCAL_APP_FAILED:
                        // 检查更新获取本地安装应用信息失败， UpdateResponse为null
                        break;
                    default:
                        break;
                }
            }
        });
        XiaomiUpdateAgent.update(this);
        
	    final Handler handler = new MainHandler(FireflyMobileActivity.this);
			
	    final Thread thread = new Thread(new Runnable(){
				@Override
				public void run() {
					try {
						//必须在初始化完成之后再执行任务
						while (true) {
							Message msg = new Message();
							Bundle data = new Bundle();
							msg.setData(data);
							String playType = sytActivityBlockingQueue.take();
							if (playType != null && playType.indexOf(MainHandler.JS_EXEC)>=0 && playType.indexOf("|")>0) {
								String js = playType.split("\\|")[1];
								playType = playType.split("\\|")[0];
								data.putString("js", js);
								data.putString("playType", MainHandler.JS_EXEC);
	//							04-01 17:25:55.873: I/SytActivity(5152): 进入jsExec|window.location.href='../module/phoTopUp/index.html'页面
							}else {
								SytLog.i("SytActivity", "进入"+playType+"页面");
								data.putString("playType", playType);
							}
							
							
							handler.sendMessage(msg);
						}
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				
			});
			//加载完毕退出全屏
//			 all = new LinearLayout(this);
//			 setContentView(all);
//			 all.addView(appView.getView());
			 super.loadUrl("file:///android_asset/www/home/index.html#/");
			 
			 YHCService yhcService = new YHCServiceImpl();
				yhcService.autoLogin();
				
				
			 Timer timer = new Timer();
			 timer.schedule(new TimerTask() {
				@Override
				public void run() {
					thread.start();
				}
			}, 2000);
    }
    
    
    private void alarmUpdate(UpdateResponse updateInfo){
    	String upVersion = updateInfo.versionName;
    	String currVersion = HomePlugin.getAppVersionName(this);
    	//version分三段，只有中段值较大时才提示升级
    	//首段将强制更新
    	if (currVersion.split("\\.")[0].compareTo(upVersion.split("\\.")[0]) < 0) {
            new AlertDialog.Builder(this).setTitle("有新版本了，赶快更新看看吧")//设置对话框标题  
            .setMessage(""+updateInfo.updateLog)//设置显示的内容  
            .setPositiveButton("立即升级",new DialogInterface.OnClickListener() {//添加确定按钮  
                @Override  
                public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件  
                    XiaomiUpdateAgent.arrange();
                }
            }).show();//在按键响应事件中显示此对话框  
		}else if (currVersion.split("\\.")[1].compareTo(upVersion.split("\\.")[1]) < 0) {
			new AlertDialog.Builder(this).setTitle("有新版本了，赶快更新看看吧")//设置对话框标题  
	        .setMessage(""+updateInfo.updateLog)//设置显示的内容  
	        .setPositiveButton("立即升级",new DialogInterface.OnClickListener() {//添加确定按钮  
	            @Override  
	            public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件  
	                XiaomiUpdateAgent.arrange();
	            }
	        }).setNegativeButton("稍后再说",new DialogInterface.OnClickListener() {//添加返回按钮  
	            @Override  
	            public void onClick(DialogInterface dialog, int which) {//响应事件  
	                Log.i("alertdialog"," 不更新，稍后再说！");  
	            }
	        }).show();//在按键响应事件中显示此对话框  
		}
        
    }
    
    
    //设置全屏 
    public void setFullscreen() {   
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);//清除FLAG   
        requestWindowFeature(Window.FEATURE_NO_TITLE);   
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,   
                       WindowManager.LayoutParams.FLAG_FULLSCREEN);   
   }   
    //退出全屏 
    public void quitFullScreen(){ 
    	final WindowManager.LayoutParams attrs = getWindow().getAttributes(); 
    	attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN); 
    	getWindow().setAttributes(attrs); 
    	getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); 
    	} 
    
    @Override  
    protected void onResume() {  
        super.onResume();
        MobclickAgent.onResume(mContext);
        //说明未登陆
        if (YHCServiceImpl.lastLoginTime != 0L) {
			//如果超过一天没登录
			if (new Date(YHCServiceImpl.lastLoginTime).before(new Date(new Date().getTime()-12*60*60*1000))) {
				YHCService yhcService = new YHCServiceImpl();
				yhcService.autoLogin();
			}
			
		}
    }
    
    @Override
    public void onPause() {
    	super.onPause();
    	MobclickAgent.onPause(mContext);
    }
    
    
}

